<template>
  <div class="receiptList">
    <el-row align="middle" class="pt-5">
      <el-col :span="16">
        <p class="main_title">{{ $t("menu.RECEIPT") }}</p>
      </el-col>
    </el-row>

    <div style="display: flex; margin: 15px;0;15px;0">
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-row :gutter="20" class="search_block pt-5">
          <el-col :span="2" class="hori-cond"><label class="form-label">状态</label></el-col>
          <el-col :span="3">
            <el-select class="formItem" v-model="searchData.jobstatus" placeholder="全部" @change="doList" clearable
              filterable>
              <el-option v-for="item in jobstatuses" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2" class="hori-cond"><label class="form-label">抓取方式</label></el-col>
          <el-col :span="3">
            <el-select class="formItem" v-model="searchData.status" placeholder="全部" @change="doList" clearable
              filterable>
              <el-option v-for="item in statuses" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <!-- <el-col :span="2" class="hori-cond"><label class="form-label">是否校验</label></el-col>
          <el-col :span="3">
            <el-select class="formItem" v-model="searchData.ischeck" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in ischecks" :key="item.value" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col> -->
          <el-col :span="9">
            <el-input class="formItem" v-model="searchData.term" placeholder="请输入公告编号\名称\主办方ID\名称" @change="doList"
              clearable>
              <el-button slot="append" icon="el-icon-search" @click="doList">查询</el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>
      <div style="flex: 0 0 20%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <div style="float:right">
          <label class="form-label">代理剩余时间：{{stateNum}}秒&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <el-button size="medium" type="primary" @click="addReceipt">新增<i
              class="el-icon-circle-plus-outline"></i></el-button>
        </div>
      </div>
    </div>

    <div style="position: sticky">
      <div class="table_container">
        <el-table v-loading="loading" :data="receipts" :header-cell-style="boxheader" :row-style="{ height: 0 + 'px' }"
          :cell-style="{ padding: 0 + 'px' }" style="width: 100%">
          <el-table-column prop="id" label="序号" min-width="60px"></el-table-column>
          <el-table-column label="公告标题" min-width="150px" align="left" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="btnCell" @click="detailReceipt(scope.row)">{{
                scope.row.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="80px" align="left" label="主办方ID" :render-header="renderheader" prop="gu_id">
            <template slot-scope="scope">
              <span>{{ scope.row.orgid }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="160px" prop="orgname" label="主办方名称" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="220px" align="left" label="公告链接" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="btnCell" @click="openUrl(scope.row.url)">{{
                scope.row.url
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="80px" align="left" label="状态" :render-header="renderheader" prop="status">
            <template slot-scope="scope">
              <span :style="{
                  color:
                    scope.row.jobstatus === 0
                      ? '#ed5b56'
                      : scope.row.jobstatus === 1
                      ? '#4190f7'
                      : scope.row.jobstatus === 2
                      ? '#72c140'
                      : '#606266'
                }">
                <span v-if="scope.row.jobstatus === 0" class="priority_notbegin">{{ $t("status.NOTBEGIN") }}</span>
                <span v-if="scope.row.jobstatus === 1" class="priority_middle">{{ $t("status.RUNNING") }}</span>
                <span v-if="scope.row.jobstatus === 2" class="priority_finished">{{ $t("status.FINISHED") }}</span>
                <el-tooltip placement="right" effect="light">
                  <div slot="content" class="joberror">
                    {{ scope.row.joberror }}
                  </div>
                  <span v-if="scope.row.jobstatus === 3" class="priority_exception" @click="showExp(scope.row.joberror)"
                    style="cursor: pointer">{{ $t("status.EXCEPTION") }}</span>
                </el-tooltip>
                <span v-if="scope.row.jobstatus === 4" class="priority_expired">{{ $t("status.EXPIRED") }}</span>
                <span v-if="scope.row.jobstatus === 5" class="priority_report">{{ $t("status.REPORT") }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="90px" align="center" label="抓取时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>
                {{ (scope.row.jobtime || " ").split(" ")[0] }}
                <br />
                {{ (scope.row.jobtime || " ").split(" ")[1] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="pagenum" label="页数" min-width="55" show-overflow-tooltip></el-table-column>
          <el-table-column prop="pager" label="增量" min-width="55" show-overflow-tooltip></el-table-column>
          <el-table-column prop="amount" label="羽数" min-width="55" show-overflow-tooltip>
            <template slot-scope="scope">
              <span :class="{ red: scope.row.ischeck === 0 }">{{
                scope.row.amount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" align="center" label="下载" :render-header="renderheader">
            <template slot-scope="scope">
              <span class="download">
                <span class="btnCell" @click="downLoad('receipt', scope.row)">收鸽清单</span>
                <span class="btnCell" @click="downLoad('score', scope.row)">成绩单</span>
                <span class="btnCell" @click="downLoad('source', scope.row)">原始文件</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="70px" align="center" label="自动抓取">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                @change="changeStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column min-width="70px" align="center" label="自动上报">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.reportstatus" :active-value="1" :inactive-value="0"
                @change="changeReport(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" align="center" :label="$t('common.OPER')" fixed="right">
            <template slot-scope="scope">
              <!-- <el-button style="margin-left: 0px !important" type="text" @click="checkReceipt(scope.row)">羽数校验</el-button> -->
              <el-button style="margin-left: 0px !important" type="text"
                @click="updateReceipt(scope.row)">{{ $t("common.UPDATE") }}</el-button>
              <el-button v-if="scope.row.jobstatus == 1" style="margin-left: 0px !important" type="text"
                @click="resetReceipt(scope.row)">重置</el-button>
              <el-button style="margin-left: 0px !important" type="text"
                @click="crawlerReceipt(scope.row)">抓取</el-button>
              <el-button style="margin-left: 0px !important" type="text"
                @click="reportReceipt(scope.row)">上报</el-button>
              <el-button style="margin-left: 0px !important" type="text"
                @click="removeReceipt(scope.row)">清理</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table_page">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchData.curpage" :page-sizes="[5, 10, 20, 50]" :page-size="searchData.pagesize"
            layout="total, sizes,  pager, jumper" :total="searchData.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 异常详情弹框 -->
    <el-dialog title="错误详情" :visible.sync="expVisible" :width="width" append-to-body>
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <textarea rows="20" nz-input v-model="expDetail" style="width: 100% !important"></textarea>
    </el-dialog>

    <el-dialog title="新增收鸽清单" :visible.sync="addVisible" :width="width" :close-on-click-modal="false">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <add-receipt-task :detailData="detailData" v-if="addVisible" @closeVisible="closeVisible"></add-receipt-task>
    </el-dialog>

    <!-- 修改弹框 -->
    <el-dialog title="修改收鸽清单" :visible.sync="updateVisible" :width="width" :close-on-click-modal="false">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <update-receipt-task :detailData="detailData" v-if="updateVisible"
        @closeVisible="closeVisible"></update-receipt-task>
    </el-dialog>

    <!-- 详情弹框 -->
    <el-dialog title="收鸽清单详情" :visible.sync="detailVisible" :width="width" :close-on-click-modal="false"
      custom-class="receiptDetailDialog">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <receipt-task-detail :detailData="detailData" v-if="detailVisible"
        @closeVisible="closeVisible"></receipt-task-detail>
    </el-dialog>

    <!-- 羽数校验弹框 -->
    <el-dialog title="羽数校验" :visible.sync="checkVisible" :width="width" :close-on-click-modal="false"
      custom-class="checkDialog">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <check-amount :detailData="detailData" v-if="checkVisible" @closeVisible="closeVisible"></check-amount>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/index";

import enlargeImg from "@/assets/images/icon_2.png";
import narrowImg from "@/assets/images/icon_3.png";
import receiptService from "@/service/receiptService";
import sponsorService from "@/service/sponsorService";
import i18n from "@/lang";

import addReceiptTask from "./components/addReceiptTask.vue";
import updateReceiptTask from "./components/updateReceiptTask.vue";
import ReceiptTaskDetail from "./components/receiptTaskDetail.vue";
import CheckAmount from "./components/checkAmount.vue";
const baseURL = process.env.BASE_API;

export default {
  name: "ReceiptList",
  components: {
    addReceiptTask,
    updateReceiptTask,
    ReceiptTaskDetail,
    CheckAmount,
  },
  data() {
    return {
      loading: false,
      jobstatuses: [
        { key: "", value: i18n.t("status.ALL") },
        { key: 0, value: i18n.t("status.NOTBEGIN") },
        { key: 1, value: i18n.t("status.RUNNING") },
        { key: 2, value: i18n.t("status.FINISHED") },
        { key: 3, value: i18n.t("status.EXCEPTION") },
        { key: 4, value: i18n.t("status.EXPIRED") },
        // {key: 5, value: i18n.t('status.REPORT')}
      ],
      statuses: [
        { key: "", value: i18n.t("status.ALL") },
        { key: 0, value: "手工抓取" },
        { key: 1, value: "自动抓取" },
      ],
      ischecks: [
        { key: "", value: i18n.t("status.ALL") },
        { key: 0, value: "未校验" },
        { key: 1, value: "已校验" },
      ],
      boxheader: {
        // background: '#eef1f6',
        color: "#606266",
        fontWeight: 800,
        borderBottom: "2px solid #EBEEF5",
      },
      searchData: {
        curpage: 1,
        pagesize: 10,
        total: 0,
      },
      receipts: [],
      staffs: [],
      width: "600px",
      expVisible: false, // 异常详情弹框
      expDetail: "", // 异常内容
      addVisible: false, // 新增抓取任务弹框
      updateVisible: false, // 修改抓取任务弹框
      detailVisible: false, // 抓取任务详情弹框
      checkVisible: false, // 羽数校验弹框
      id: "", // 羽数校验Id
      detailData: "",
      iconImg: enlargeImg,
      stateNum: 100,
    };
  },
  watch: {},
  mounted: function () {
    // console.log(window.screen.height);
    this.$store.dispatch("setActive", "10").then(() => {
      // this.$root.eventBus.$emit('exit')
    });
    // commit('SET_ACTIVE', 5)
  },
  created() {
    this.ELHeight = window.screen.height - 320;
    if (window.screen.height === 900) {
      this.ELHeight = 460;
    }
    this.doTimer();
    this.doList();
  },
  destroyed() {},
  methods: {
    parseTime,
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1]),
      ]);
    },
    // 展示异常弹框
    showExp(data) {
      this.expVisible = true;
      this.expDetail = data;
    },
    doTimer() {
      receiptService.remainder({}).then((res) => {
        if (res.status === 200 && res.data.result === 0) {
          this.stateNum = res.data.data;
          this.showTimer();
        }
      });
    },
    showTimer() {
      let timer = setInterval(() => {
        this.stateNum--;
        if (this.stateNum === 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    doList(type) {
      if (type != "update") {
        this.searchData.curpage = 1;
      }
      this.listReceipt();
    },
    listReceipt() {
      this.loading = true;
      let searchData = { ...this.searchData };
      delete searchData.total;
      let params = searchData;
      receiptService.listReceipt(params).then((res) => {
        this.loading = false;
        if (res.status === 200 && res.data.result === 0) {
          this.receipts = res.data.data;
          this.searchData.total = res.data.total;
        }
      });
    },
    // 根据id获取负责人姓名
    getValueById(id, arr) {
      let obj = arr.find((item) => item.id == id);
      return obj && obj.name ? obj.name : "";
    },
    // 详情
    detailReceipt(row) {
      this.detailData = JSON.stringify(row);
      this.detailVisible = true;
    },
    addReceipt() {
      let vdata = {};
      sponsorService.zxwOrganizers({}).then((res) => {
        if (res && res.data.result === 0) {
          vdata.orgsels = res.data.data;
        }
        this.detailData = JSON.stringify(vdata);
        this.addVisible = true;
      });
    },
    // 修改
    updateReceipt(row) {
      let vdata = row;
      sponsorService.zxwOrganizers({}).then((res) => {
        if (res && res.data.result === 0) {
          vdata.orgsels = res.data.data;
        }
        this.detailData = JSON.stringify(vdata);
        this.updateVisible = true;
      });
    },
    // 羽数校验弹框
    checkReceipt(row) {
      this.detailData = JSON.stringify(row);
      this.checkVisible = true;
    },
    // 变更抓取方式
    changeStatus(row) {
      let params = { id: row.id, status: row.status };
      receiptService.updateStatus(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("操作成功!");
        } else {
          this.$message.error("操作失败！");
        }
        this.listReceipt();
      });
    },
    // 变更上报方式
    changeReport(row) {
      let params = { id: row.id, reportstatus: row.reportstatus };
      receiptService.updateReport(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("操作成功!");
        } else {
          this.$message.error("操作失败！");
        }
        this.listReceipt();
      });
    },
    // 重置任务
    resetReceipt(row) {
      let params = { id: row.id, orgid: row.orgid };
      receiptService.resetReceipt(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("重置成功!");
        } else {
          this.$message.error("重置失败！");
        }
        this.listReceipt();
      });
    },
    // 立刻抓取
    crawlerReceipt(row) {
      let params = { id: row.id, jobstatus: 1 };
      receiptService.updateReceipt(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("操作成功!");
        } else {
          this.$message.error("操作失败！");
        }
        this.listReceipt();
      });
    },
    reportReceipt(row) {
      let params = { id: row.id };
      receiptService.reportReceipt(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("操作成功!");
        } else {
          this.$message.error("操作失败！");
        }
        this.listReceipt();
      });
    },
    removeReceipt(row) {
      this.$confirm("删除源文件后不能恢复，请慎重操作或提前下载备份", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = { id: row.id };
          receiptService.removeReceipt(params).then((res) => {
            if (res && res.data.result === 0) {
              this.$message.success("删除成功!");
            } else {
              this.$message.error("删除失败！");
            }
            this.listReceipt();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 立刻上传
    uploadReceipt(row) {
      let params = { userId: row.mysql_organizer_user_id };
      receiptService.upload(params).then((res) => {
        if (res.data.msg === "ok") {
          this.$message.success("操作成功！");
          this.listReceipt();
        }
      });
    },
    // 打开公告链接
    openUrl(url) {
      window.open(url, "_blank");
    },
    // 下载原始数据
    downLoad(type, row) {
      if (type === "receipt") {
        this.$message.info("正在下载收鸽清单...");
        window.open(baseURL + "/receipt/download/xls?id=" + row.id, "_self");
      } else if (type === "score") {
        this.$message.info("正在下载成绩单...");
        window.open(baseURL + "/receipt/download/race?id=" + row.id, "_self");
      } else {
        this.$message.info("正在下载原始文件...");
        window.open(baseURL + "/receipt/download/txt?id=" + row.id, "_self");
      }
      /* if (type === 'source') {
        receiptService.downLoad(row.id).then(res => {
          let resFile = res.headers['content-disposition']
          let fileName = resFile.match(/=(.*)$/)[1];
          let blob = new Blob([res.data], {type: res.headers['content-type']});
          let objectUrl = URL.createObjectURL(blob);
          let a = document.createElement('a');
          a.href = objectUrl;
          console.log(objectUrl, 'objectUrl')
          a.download = fileName;
          a.click();
        })
      }*/
    },
    handleSizeChange(val) {
      this.searchData.pagesize = val;
      this.listReceipt();
    },
    handleCurrentChange(val) {
      this.searchData.curpage = val;
      this.listReceipt();
    },
    enlarge() {
      if (this.width === "600px") {
        this.width = "1000px";
        this.iconImg = narrowImg;
      } else {
        this.width = "600px";
        this.iconImg = enlargeImg;
      }
    },
    closeVisible(type) {
      this.addVisible = false;
      this.updateVisible = false;
      this.checkVisible = false;
      this.detailVisible = false;
      if (type !== "cancel") {
        this.doList(type);
      }
    },
  },
};
</script>

<style>
.main_title {
  color: #343434;
  font-size: 18px;
  margin: 7px 0 0 0;
}

.area-detail {
  margin-top: 0px;
}

.define_label {
  line-height: 25px;
  text-align: left;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 340px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.define_span {
  line-height: 25px;
  text-align: right;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 480px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-back {
  width: 90%;
  /*height: 209px;*/
  background: rgba(233, 233, 233, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.message-task {
  width: 90%;
  /*height: 209px;*/
  background: rgba(203, 225, 203, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.joberror {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item {
  margin-top: 10px;
  padding-top: 5px;
  margin-right: 15px;
}
.receiptList .sponsorCell {
  vertical-align: middle;
}
.receiptList .sponsorLink {
  margin-left: 3px;
  text-decoration: none;
  color: #1890ff;
}
.btnCell {
  color: #1890ff;
  cursor: pointer;
}
.download .btnCell {
  border-right: 1px solid #eee;
  padding: 0px 5px;
  display: inline-block;
}
.download .btnCell:nth-last-child(1) {
  border-right: 0px;
  padding-right: 0px;
}
.table_page {
  background: #fff !important;
  padding: 10px;
  text-align: right;
}
.receiptDetailDialog .el-dialog__body {
  padding: 10px 20px 30px !important;
}
.formItem {
  width: 100%;
}
.red {
  color: #f56c6c;
}
</style>
